package io.chain.ko.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import io.chain.ko.common.Const;
import io.chain.ko.entity.TUser;
import io.chain.ko.service.JWTTokenService;
import io.chain.ko.service.UserService;
import io.chain.ko.util.AuthUtils;


public class JWTAuthFilter extends OncePerRequestFilter  {
	
	private JWTTokenService jwtTokenService;
	private UserService userService;
	private Long tokenTimeout;
	
	public JWTAuthFilter(JWTTokenService jwtTokenService, UserService userService,Long tokenTimeout) {
		this.jwtTokenService = jwtTokenService;
		this.userService = userService;
		this.tokenTimeout=tokenTimeout;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String authorization=request.getHeader(Const.AUTHORIZATION);
		String bearer=Const.BEARER;
		TUser tuser=null;
		SecurityContextHolder.getContext().setAuthentication(null);
		if(authorization!=null && authorization.startsWith(bearer)) {
			String token=authorization.substring(bearer.length());
			String username=jwtTokenService.parseToken(token);
			if(StringUtils.isNotEmpty(username)) {
				tuser=userService.findByUsername(username);
				if(tuser!=null && StringUtils.isNotEmpty(tuser.getToken())) {
					Long tokenTime=tuser.getTokenTime().getTime();
					Long currentTime=System.currentTimeMillis();
					if(tuser.getToken().equals(authorization) && currentTime<tokenTime+tokenTimeout) {						
						UsernamePasswordAuthenticationToken authentication=new UsernamePasswordAuthenticationToken(tuser.getUsername(),
						tuser.getPassword(),AuthUtils.buildAuth(tuser.getRoles()));
						SecurityContextHolder.getContext().setAuthentication(authentication);
						tuser.setTokenTime(new Date());
						userService.updateUser(tuser);
					}
				}
			}
		}		
		filterChain.doFilter(request, response);
	}

}
